package com.rjwh.dingdong.client.adapter;

import android.content.Context;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.daimajia.numberprogressbar.NumberProgressBar;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.bean.localbean.DownloadInfo;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.download.DownloadManager;
import com.rjwh.dingdong.client.download.ZipUnTask;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.RxBus;
import com.wby.base.AdapterBase;

import rx.Observable;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * 项目名称：whrjwh-parent
 * 类描述：
 * 创建人：wby
 * 创建时间：2016/6/27 11:01
 * 修改人：wby
 * 修改时间：2016/6/27 11:01
 * 修改备注：
 *
 */
public class DowloadListAdapter extends AdapterBase<DownloadInfo>  {

    private Context context;
    private ListView listview;
    private Observable<DownloadInfo> observable;
    private Observable<DownloadInfo> observableChange;
    private Observable<DownloadInfo> observableProg;

    private Subscription subscriptionUnZip;
    private Subscription subscriptionChange;
    private Subscription subscriptionProg;

    public DowloadListAdapter(Context context, ListView listView) {
        this.listview = listView;
        this.context = context;
    }

    public void startObserver() {

        observable = RxBus.get().register(LocalConstant.RX__POST_DOWNLOAD_STATE_UNZIP, DownloadInfo.class);

        observableChange = RxBus.get().register(LocalConstant.RX__POST_DOWNLOAD_STATE_CHANGE, DownloadInfo.class);

        observableProg = RxBus.get().register(LocalConstant.RX__POST_DOWNLOAD_STATE_PROGRES, DownloadInfo.class);

        subscriptionUnZip = observable.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<DownloadInfo>() {
                    @Override
                    public void call(DownloadInfo localGmaeInfo) {

                        for (int i = 0; i < getCount(); i++) {
                            DownloadInfo appInfo = (DownloadInfo) getItem(i);
                            if (appInfo.getGameId() == localGmaeInfo.getGameId()) {
                                if (localGmaeInfo.getDownloadState() == DownloadManager.STATE_UNZIP_SUCESS) {
                                    mList.remove(i);
                                    notifyDataSetChanged();
                                } else {
                                    updataView(i, appInfo, listview);
                                }
                            }
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtil.d("DowloadListAdapter", throwable.getMessage());
                    }
                });

        subscriptionChange = observableChange.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<DownloadInfo>() {
                    @Override
                    public void call(DownloadInfo localGmaeInfo) {

                        refreshHolder(localGmaeInfo);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtil.d("DowloadListAdapter", throwable.getMessage());
                    }
                });

        subscriptionProg =  observableProg.observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<DownloadInfo>() {
                    @Override
                    public void call(DownloadInfo localGmaeInfo) {

                        refreshHolder(localGmaeInfo);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        LogUtil.d("DowloadListAdapter", throwable.getMessage());
                    }
                });

    }

    public void stopObserver() {
        //释放销毁内存
        if(subscriptionUnZip!=null && !subscriptionUnZip.isUnsubscribed()){
            subscriptionUnZip.unsubscribe();
        }
        if(subscriptionChange!=null && !subscriptionChange.isUnsubscribed()){
            subscriptionChange.unsubscribe();
        }
        if(subscriptionProg!=null && !subscriptionProg.isUnsubscribed()){
            subscriptionProg.unsubscribe();
        }
        RxBus.get().unregister(LocalConstant.RX__POST_DOWNLOAD_STATE_UNZIP, observable);
        RxBus.get().unregister(LocalConstant.RX__POST_DOWNLOAD_STATE_CHANGE, observableChange);
        RxBus.get().unregister(LocalConstant.RX__POST_DOWNLOAD_STATE_PROGRES, observableProg);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }



    private void refreshHolder(final DownloadInfo info) {
        for (int i = 0; i < getCount(); i++) {
            DownloadInfo appInfo = (DownloadInfo) getItem(i);
            if (appInfo.getGameId() == info.getGameId()) {
                getList().set(i, info);
                updataView(i, info, listview);
            }
        }
    }

    public class ViewHolder {
        public TextView tvAppNmae, tvDownloadSize,tvNetSeed;
        public Button button;
        private NumberProgressBar pbr;
        public DownloadInfo mData;
        private DownloadManager mDownloadManager;
        protected View mRootView;
        private ImageView imgPic;
        private ImageView img;



        public ViewHolder() {
            if (mDownloadManager == null) {
                mDownloadManager = DownloadManager.getInstance();
            }
            mRootView = initView();
            mRootView.setTag(this);

        }

        public View getRootView() {
            return mRootView;
        }

        public DownloadInfo getData() {
            return mData;
        }

        public View initView() {
            View view = LayoutInflater.from(context).inflate(R.layout.dowload_manger_list_item, null);

            img = (ImageView) view
                    .findViewById(R.id.download_manager_img);
            tvAppNmae = (TextView) view
                    .findViewById(R.id.download_manager_appname_tv);
            tvDownloadSize  = (TextView) view
                    .findViewById(R.id.download_manager_downloadSize_tv);

            tvNetSeed =  (TextView) view
                    .findViewById(R.id.download_manager_netSpeed_tv);

            button = (Button) view.findViewById(R.id.download_manager_start_btn);
            pbr = (NumberProgressBar) view.findViewById(R.id.download_manager_progressBar);
            imgPic = (ImageView) view.findViewById(R.id.download_manager_img);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int mState = mData.getDownloadState();
                    if (mState == DownloadManager.STATE_NONE
                            || mState == DownloadManager.STATE_PAUSED
                            || mState == DownloadManager.STATE_ERROR) {
                        mDownloadManager.addTask(mData);
                    } else if (mState == DownloadManager.STATE_WAITING
                            || mState == DownloadManager.STATE_DOWNLOADING) {
                        mDownloadManager.pauseTask(mData.getGameId());
                    } else if (mState == DownloadManager.STATE_DOWNLOADED ) {
                        new Thread(new ZipUnTask(mData)).start();
                    }
                }
            });
            return view;
        }

        public void setData(DownloadInfo data) {

            mData = data;
            refreshView();

        }

        public void refreshView() {
            Glide.with(context).load(mData.getGamePic()).placeholder(R.drawable.icon_pic_holder).error(R.drawable.icon_pic_holder).dontAnimate().into(img);
            tvAppNmae.setText(mData.getGameName());
            pbr.setProgress((int)mData.getProgress());

            refreshState();
        }

        public void refreshState() {
            String downloadLength = Formatter.formatFileSize(context, mData.getDownloadLength());
            String totalLength = Formatter.formatFileSize(context, mData.getTotalLength());
            tvDownloadSize.setText(downloadLength + "/" + totalLength);

            switch (mData.getDownloadState()) {
                case DownloadManager.STATE_NONE:
                    button.setText("开始");
                    tvNetSeed.setText("");
                    break;
                case DownloadManager.STATE_PAUSED:
                    button.setText("暂停");
                    tvNetSeed.setText("");
                    break;
                case DownloadManager.STATE_ERROR:
                    button.setText("下载失败");
                    tvNetSeed.setText("");
                    break;
                case DownloadManager.STATE_WAITING:
                    button.setText("等待");
                    tvNetSeed.setText("");
                    break;
                case DownloadManager.STATE_DOWNLOADING:
                    button.setText("下载中");
                    String networkSpeed = Formatter.formatFileSize(context, mData.getNetworkSpeed());
                    tvNetSeed.setText(networkSpeed+"/s");
                    pbr.setProgress((int)mData.getProgress());
                    break;
                case DownloadManager.STATE_DOWNLOADED:
                    button.setText("下载完成");
                    tvNetSeed.setText("");
                    break;
                case DownloadManager.STATE_UNZIP:
                    button.setText("解压中");
                    tvNetSeed.setText("");
                    break;
                case DownloadManager.STATE_UNZIP_SUCESS:
                    button.setText("解压成功");
                    tvNetSeed.setText("");
                    break;
//                 case DownloadManager.STATE_READ:
                // button.setText(R.string.app_state_read);
                // break;
                default:
                    break;
            }
        }
    }

    @Override
    protected View getExView(int position, View convertView, ViewGroup parent)
            throws Exception {
        // TODO Auto-generated method stub
        final DownloadInfo appInfo = getList().get(position);

        final ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        holder.setData(appInfo);
        return holder.getRootView();
    }

    @Override
    protected void onReachBottom() {

    }

    public void updataView(int posi, final DownloadInfo info, ListView listView) {
        int visibleFirstPosi = listView.getFirstVisiblePosition();
        int visibleLastPosi = listView.getLastVisiblePosition();
        if (posi >= visibleFirstPosi && posi <= visibleLastPosi) {
            View view = listView.getChildAt(posi - visibleFirstPosi);
            ViewHolder holder = (ViewHolder) view.getTag();
            holder.setData(info);
        }
    }
}
